package club.classload;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class UrlLoaderClass extends ClassLoader{
    String rootUrl;
    public UrlLoaderClass(String rootUrl){
        this.rootUrl=rootUrl;
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class<?> c=findLoadedClass(name);
        if(c!=null){
            return c;
        }else{
            ClassLoader parent = this.getParent();
            try {
                c = parent.loadClass(name);
            }catch(Exception e){

            }
            if(c!=null){
                return c;
            }else{
                byte[] classData=getclassData(name);
                if(classData==null){
                    throw new ClassNotFoundException();
                }else{
                   c= defineClass(classData,0,classData.length);
                }
            }
        }
        return c;
    }
    private byte[] getclassData(String name){
        String path=rootUrl+"/"+name.replace(".","/")+".class";
        InputStream is=null;
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        try {
            URL url = new URL(path);
             is=url.openStream();

            byte[] bytes=new byte[1024];
            int temp=0;
            while((temp=is.read(bytes))!=-1){
                baos.write(bytes,0,bytes.length);
            }
            return baos.toByteArray();
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally {
            if(is!=null){
                try{
                    is.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }

        }

    }
}
